/**
 * 
 */
package sensorBoard.io;

import com.CharNotValidException;
import com.Event;
import com.ParamsLabel;
 
import sensorBoard.ISensorBoardComponent;
import server.interfaces.ISensorBoardManager;
import com.sun.spot.peripheral.Spot;
import com.sun.spot.peripheral.IBattery;
 

/**
 * BatteryManager manages the access to the node's Battery.
 * @author Francesco Aiello, Antonio Guerrieri, Raffaele Gravina
 *
 */
public class Battery implements ISensorBoardComponent {

	private byte [] handlableEvents = {Event.BTR_CURRENT_LEVEL};
	
	private ISensorBoardManager sensorBoardManager;
	
	public Battery (ISensorBoardManager sensorBoardManager) {
		this.sensorBoardManager = sensorBoardManager;
	}
	
	/* (non-Javadoc)
	 * @see sensorBoard.ISensorBoardComponent#IsEventHandlable(byte)
	 */
	public boolean IsEventHandlable(byte eventName) {
		for (int i = 0; i < handlableEvents.length; i++) 
			if (this.handlableEvents[i] == eventName)
				return true;
		return false;
	}

	/* (non-Javadoc)
	 * @see sensorBoard.ISensorBoardComponent#handleEvent(com.Event)
	 */
	public void handleEvent(Event event) {
		
		byte eventName = event.getName();
		switch (eventName) {
			case Event.BTR_CURRENT_LEVEL:
				IBattery battery = Spot.getInstance().getPowerController().getBattery();
				int batteryLevel = battery.getBatteryLevel();
				try {
					Event backEvent = new Event(event.getSourceID(), event.getSourceID(), Event.BTR_CURRENT_LEVEL, Event.NOW);
					backEvent.setParam(ParamsLabel.BTR_CURRENT_LEVEL, "" + batteryLevel);
					this.send(backEvent);
				} catch (CharNotValidException e) {
					e.printStackTrace();
				}
				
			break;
		}
		this.send(event);

	}

	/* (non-Javadoc)
	 * @see sensorBoard.ISensorBoardComponent#send(com.Event)
	 */
	public void send(Event backEvent) {
		this.sensorBoardManager.send(backEvent);
	}

	/* (non-Javadoc)
	 * @see sensorBoard.ISensorBoardComponent#terminateListener(java.lang.String)
	 */
	public boolean terminateListener(String sensorID) {
		// TODO Auto-generated method stub
		return false;
	}

}
